package com.qmock.pay.umpay.handler;

import com.qmock.pay.http.ExpectResponse;
import com.qmock.pay.http.ExpectResponseInterface;
import com.qmock.pay.runner.Service;
import com.qmock.pay.umpay.service.UmpayService;
import org.apache.log4j.Logger;
import org.webbitserver.HttpControl;
import org.webbitserver.HttpHandler;
import org.webbitserver.HttpRequest;
import org.webbitserver.HttpResponse;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.Map;

/**
 * @author
 */
public class UmpayHttpHandler implements HttpHandler {
    private static Logger logger = Logger.getLogger(UmpayHttpHandler.class);
    private String url;
    private Service umpayServiceInterface;
    private ExpectResponseInterface expectResponse;
    public UmpayHttpHandler(ExpectResponseInterface expectResponse, Service service,String url) {
        logger.info("初始化了UmpayHttpHandler控制器...");
        this.expectResponse=expectResponse;
        this.umpayServiceInterface=service;
        this.url=url;
    }

    public UmpayHttpHandler(ExpectResponseInterface expectResponse,String url) {
        logger.info("初始化了UmpayHttpHandler控制器...");
        this.expectResponse=expectResponse;
        this.url=url;
    }


    @Override
    public synchronized void handleHttpRequest(HttpRequest request, HttpResponse response, HttpControl control) throws Exception {
    	synchronized (this) {
    		try{
                logger.info("开始解析请求参数.......");
                if(request.uri().contains(url.replace("/", ""))){
                    logger.info("拦截到了来自"+((InetSocketAddress)request.remoteAddress()).getAddress().getHostAddress()+"的请求,请求的URL为"+url.replaceAll("/",""));
                    UmpayHttpRequest umpayHttpResquest=new UmpayHttpRequest(request);
                    if(umpayHttpResquest.requestParameterPair.size()==0){
                        response.charset(Charset.forName("UTF-8")).header("Content-type", "text/html").content("Welcome to the Mock of Umpay...").end();
                    }else{
                        if(umpayServiceInterface==null){
                            String serviceName = umpayHttpResquest.getService();
                            logger.info("拦截解析到请求的服务名为-->"+serviceName);
                            UmpayService umpayService = Enum.valueOf(UmpayService.class, serviceName.toUpperCase());
                            umpayServiceInterface=umpayService.service(umpayHttpResquest);
                            logger.info("请求到的服务名称为->"+serviceName);
                        }else{
                            logger.info("请求到的服务名称为->"+umpayHttpResquest.getService());
                        }
                        response.charset(Charset.forName("UTF-8"));
                        if(expectResponse!=null){
                            response.charset(Charset.forName("UTF-8")).header("Content-type", "text/html").content(umpayServiceInterface.getHttpResponseContent((ExpectResponse) expectResponse)).end();
                            printMap(umpayServiceInterface.getResponseParameters());
                            logger.info(umpayServiceInterface.getHttpResponseContent((ExpectResponse) expectResponse));
                        }else{
                            response.charset(Charset.forName("UTF-8")).header("Content-type", "text/html").content(umpayServiceInterface.getHttpResponseContent()).end();
                            printMap(umpayServiceInterface.getResponseParameters());
                            logger.info(umpayServiceInterface.getHttpResponseContent());
                        }
                        umpayHttpResquest=null;
                    }
                }else{
                    //response.error(new Exception("访问的URL不存在，请修改后再重新访问。"));
                    response.status(404).end();
                }
            }catch (Exception e){
                response.write(e.getMessage());
                e.printStackTrace();
            }
    		
		}
    	 
    }

    private void printMap(Map<String,String> map){
        for(Map.Entry<String,String> entry:map.entrySet()){
            logger.info("响应的参数-->"+" key: "+entry.getKey()+", value: "+entry.getValue());
        }
    }
    public void set(ExpectResponseInterface expectResponseInterface){
        this.expectResponse=expectResponseInterface;
    }



   
}
